import { createRouter, createWebHistory } from 'vue-router'
import loginView from "../views/userLogin.vue"
import layout from "../layout/layoutIndex.vue"
import { useLayout } from '../stores/layout'
import { getuserinfo } from '../api/userinfo'
import { renderroute } from '../util/base'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: "hash",
  routes: [
    {
      path: '/',
      name: 'home',
      component: layout,
      meta: {
        title: "首页"
      },
      children: [
        // { path: "a", component: () => import("../views/novelA.vue") },
        { path: "b", component: () => import("../views/novelB.vue") },
      ]
    },

    {
      path: "/",
      name: "a",
      component: layout,
      children: [{ path: "a", component: () => import("../views/novelA.vue") },]
    },


    {
      path: '/login',
      name: 'login',
      component: loginView
    },

    {
      path: "/404",
      name: "404",
      component: layout,
      children: [{ path: "", component: () => import("../components/nofound/nofound.vue") },]

    },

  ]
})

var whileList = ["/login"]
router.beforeEach(async (to, from, next) => {
  let store = useLayout()
  if (whileList.includes(to.path)) {
    next()
    return
  }
  if (!localStorage.getItem("token")) {
    console.log("去 登录页面");
    next({ name: "login" })
  } else {
    // 正常进入之前, 渲染菜单页面

    if (store.menus.length == 0) {
      //  表示需要去渲染菜单
      //  需要发送请求去获取菜单数据

      let { data } = await getuserinfo()
      console.log("用户信息", data.permissionList);
      let menu = renderroute(data.permissionList)
      console.log(menu);
      store.menus = menu

      //  当菜单创建完毕以后
      menu.forEach(v => {
        router.addRoute("home", v)
      })
      router.addRoute("home", {
        path: '/:pathMatch(.*)',
        redirect: '/404',
      },)

      next(to.path, { replace: true })
      // [ /  , http://127.0.0.1:5173/getnovel , ]
    } else {

      store.currentRouter = router.currentRoute.value.matched.map((v) => {
        return {
          title: v.meta.title,
          path: v.path
        }
      })



      next()
    }





  }







})


export default router
